import React from 'react';
import { Form, Input } from 'antd';
import type { ChildrenType, Modify } from '../typings';
import type { ColProps } from 'antd/es/grid/col';
import type { FormInstance, FormItemProps } from 'antd';
import _ from 'lodash';

const TjFormItem: React.FC<ITjFormItemProps> = (props) => {
  function getControl(): ChildrenType {
    let control = null;
    const children: any = props.render || props.children;
    if (children) {
      if (_.isFunction(children) && props.form) {
        control = children(props.form);
      } else {
        control = children;
      }
    } else {
      control = <Input />;
    }

    // 以下判断不是100%准确 不同antd版本不同 此判断只针对当前antd4.x版本
    const controlProps: any = {
      allowClear: _.get(props, 'allowClear', true),
      placeholder: `请输入${props.label}`,
    };

    if (control.type && control.type.SECRET_COMBOBOX_MODE_DO_NOT_USE) {
      controlProps.placeholder = `请选择${props.label}`;
    }

    if (_.isString(props.placeholder)) {
      controlProps.placeholder = props.placeholder;
    }

    if (control.type.name && control.type.name.indexOf('Input') > -1) {
      controlProps.maxLength = _.get(props, 'maxLength', 300);
    }

    if (!props.label && !props.placeholder) {
      delete controlProps.placeholder;
    }
    return React.cloneElement(control, _.merge({}, controlProps, control.props));
  }

  const { form, render, children, ...stdProps } = props;

  return <Form.Item {...stdProps}>{getControl()}</Form.Item>;
};

export interface ITjFormItemProps extends ITjFormItem {
  /**
   * 等同于 children 习惯问题
   * 传入符合antd表单控件的组件
   * @default `<Input />`
   */
  render?: ChildrenType;

  /**
   * 表单实例对象
   * 在配合TjForm使用时会自动传入
   */
  form?: FormInstance | null;

  /**
   *
   *  支持直接传入placeholder
   */
  placeholder?: string;

  /**
   * maxLength 只针对input并且默认10
   */
  maxLength?: number;

  /**
   * 输入框自带自动清除按钮
   */
  allowClear?: false;

  /**
   *
   * TjForm使用了useGrid即可生效
   * 优先级比useGrid高
   */
  col?: ColProps;
}

type ITjFormItem = Modify<
  FormItemProps,
  {
    /**
     * 传入符合antd表单控件的组件
     * @default `<Input />`
     */
    children?: ChildrenType;
  }
>;

export { TjFormItem };
